import { login, signup, logout, getInfo } from '@/API/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const member = {
  state: {
    token: getToken() || '',
    memberId: '',
    name: ''
  },

  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
    },
    SET_NAME(state, name) {
      state.name = name
    },
    // SET_POWER(state, power) {
    //   state.power = power
    // },
    SET_MEMBERID(state, memberId) {
      state.memberId = memberId
    }
  },
  actions: {
    // phone+password
    Login({ commit }, { phone, password }) {
      return login({ phone, password }).then((response) => {
        const data = response.data.result
        // cookie存储
        setToken(data.token)
        // vuex存储
        commit('SET_MEMBERID', data.memberId)
        commit('SET_TOKEN', data.token)
      })
    },
    // 点击登出按钮，主动登出
    Logout({ commit, state }) {
      return logout(state.memberId).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_MEMBERID', '')
        removeToken()
      })
    },
    // token 过期时登出
    FedLogout({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },
    // 获取用户信息
    GetInfo({ commit }) {
      return getInfo().then((response) => {
        const data = response.data.result
        // commit('SET_POWER', data.power)
        commit('SET_MEMBERID', data.memberId)
        commit('SET_NAME', data.name)
        return data
      })
    },
    Signup({ commit, state }, memberInfo) {
      return signup(memberInfo).then((response) => {
        const data = response.data.result
        setToken(data.token)
        commit('SET_MEMBERID', data.memberId)
        commit('SET_TOKEN', data.token)
      })
    }
  }
}
export default member
